﻿using SuperJoe.Framework.Caching;
using SuperJoe.Framework.Common;
using SuperJoe.Framework.Core;
using SuperJoe.Framework.Ioc;
using SuperJoe.Framework.Logging;
using SuperJoe.Framwork.Web;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace WWX.MemberPortal.Web
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {

            IdentityManager.ClaimTypeUser = "wwx_member_portal";
            IdentityManager.CookieName = "wwx_member_portal";

            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            IocManager.Init(new List<string>() { "WWX.MemberPortal.DAL", "WWX.MemberPortal.IDAL" });
            LoggerUtil.Init(IocManager.Container.Resolve<ILogger>());


            using (LoggerUtil.BlockInfo("****************************应用程序开始初始化****************************", "****************************应用程序初始化结束****************************"))
            {
                AreaRegistration.RegisterAllAreas();
                FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
                RouteConfig.RegisterRoutes(RouteTable.Routes);
                BundleConfig.RegisterBundles(BundleTable.Bundles);
                CacheManager.Init(ConfigUtil.GetValue<string>("RedisConn"));
                SuperJoeContext.SetResolver(new ContextResolver());
            }



        }

        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Exception ex = e.ExceptionObject as Exception;
            if (ex != null)
            {
                LoggerUtil.Error("系统未处理异常", ex);
            }
            else
            {
                LoggerUtil.Error("系统未处理异常，并且异常对象为空");
            }
        }

        protected void Application_Error(object sender, EventArgs e)
        {
            var error = Server.GetLastError();

            try
            {

                var errorSb = new StringBuilder();
                var urlReferrer = HttpContext.Current.Request.UrlReferrer;
                errorSb.AppendFormat("\r\nRequest Url：{0}", HttpContext.Current.Request.Url.AbsolutePath);
                if (urlReferrer != null)
                {
                    errorSb.AppendFormat("\r\nUrl Referrer：{0}", urlReferrer.AbsolutePath);
                }

                LoggerUtil.Error(errorSb.ToString(), error);
            }
            catch (Exception ex)
            {
                LoggerUtil.Error("在Application_Error方法执行出现异常:" + ex.ToString() + "。原始异常：" + error.ToString());
            }
            finally
            {
                Server.ClearError();
            }
        }
    }
}
